package cn.tedu.knows.search.controller;

import cn.tedu.knows.commons.vo.Topic;
import cn.tedu.knows.search.service.IQuestionService;
import cn.tedu.knows.search.vo.QuestionVo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class QuestionConsumer {
    @Resource
    private IQuestionService questionService;

    //kafka监听器指定话题名称
    //在该话题出现信息自动调用下面的方法
    @KafkaListener(topics = Topic.QUESTIONS)
    public void questionReceive(
            ConsumerRecord<String,String> record
    ){
        //获得问题消息,转换成问题对象
        String json = record.value();
        Gson gson = new Gson();
        QuestionVo questionVo = gson.fromJson(
                json,QuestionVo.class
        );
        //调用业务逻辑层方法执行新增操作
        questionService.saveQuestion(questionVo);
        log.debug("成功的新增了信息到ES:{}",questionVo);
    }
}
